package com.market.fleamarket.controller;

import com.market.fleamarket.entity.Review;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/reviews")
public class ReviewController {
    @Autowired
    private ReviewService reviewService;

    @PostMapping
    public ResponseEntity<?> addReview(@RequestBody Review review) {
        try {
            return ResponseEntity.ok(reviewService.save(review));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "添加评价失败: " + e.getMessage()));
        }
    }

    @GetMapping
    public ResponseEntity<?> getAllReviews() {
        try {
            return ResponseEntity.ok(reviewService.findAll());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取评价列表失败: " + e.getMessage()));
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getReviewById(@PathVariable Long id) {
        try {
            return ResponseEntity.ok(reviewService.findById(id).orElse(null));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取评价失败: " + e.getMessage()));
        }
    }

    @GetMapping("/order/{orderId}")
    public ResponseEntity<?> getReviewByOrderId(@PathVariable Long orderId, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return ResponseEntity.status(401).body(Collections.singletonMap("error", "请先登录"));
            }

            Optional<Review> review = reviewService.findByOrderId(orderId);
            if (review.isPresent()) {
                return ResponseEntity.ok(review.get());
            } else {
                return ResponseEntity.ok(new HashMap<String, Object>() {{
                    put("message", "未找到该订单的评价");
                }});
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取评价失败: " + e.getMessage()));
        }
    }

    @PostMapping("/order/{orderId}")
    public ResponseEntity<?> addReview(@PathVariable Long orderId, @RequestBody Review review, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return ResponseEntity.status(401).body(new HashMap<String, Object>() {{
                    put("error", "未登录");
                }});
            }
            return ResponseEntity.ok(reviewService.addReview(orderId, review, user.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> response = new HashMap<>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/seller/{sellerId}")
    public ResponseEntity<?> getSellerReviews(@PathVariable Long sellerId,
                                              @RequestParam(defaultValue = "0") int page,
                                              @RequestParam(defaultValue = "10") int size) {
        try {
            System.out.println("获取卖家评价: sellerId = " + sellerId + ", page = " + page + ", size = " + size);
            Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
            Page<Review> reviews = reviewService.findByProductSeller(sellerId, pageable);
            System.out.println("找到评价数量: " + reviews.getTotalElements());
            return ResponseEntity.ok(reviews);
        } catch (Exception e) {
            System.err.println("获取卖家评价时出错: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取卖家评价失败: " + e.getMessage()));
        }
    }

    /**
     * 获取特定卖家商品的评价
     * 这个API接口供前端页面使用，返回特定卖家的评价列表
     */
    @GetMapping("/seller/{sellerId}/product")
    public ResponseEntity<?> getSellerProductReviews(@PathVariable Long sellerId) {
        try {
            System.out.println("获取卖家商品评价: sellerId = " + sellerId);
            List<Map<String, Object>> reviews = reviewService.findReviewsBySellerId(sellerId);
            System.out.println("找到评价数量: " + reviews.size());
            return ResponseEntity.ok(reviews);
        } catch (Exception e) {
            System.err.println("获取卖家商品评价时出错: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取卖家商品评价失败: " + e.getMessage()));
        }
    }

    @GetMapping("/my-reviews")
    public ResponseEntity<?> getMyReviews(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return ResponseEntity.status(401).body(Collections.singletonMap("error", "请先登录"));
            }

            List<Review> reviews = reviewService.findByReviewerId(user.getId());
            return ResponseEntity.ok(reviews);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "获取我的评价失败: " + e.getMessage()));
        }
    }

    /**
     * 获取特定商品的评价
     * @param productId 商品ID
     * @return 评价列表
     */
    @GetMapping("/product/{productId}")
    public ResponseEntity<?> getProductReviews(@PathVariable Long productId) {
        List<Map<String, Object>> reviews = reviewService.findReviewsByProductId(productId);
        System.out.println("找到商品ID " + productId + " 的评价数量: " + reviews.size());
        return ResponseEntity.ok(reviews);
    }
} 